package com.example.demo.controller;

import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;


    @Autowired
    private TransactionDefinition definition;

    @RequestMapping("/registry")
    @Transactional(rollbackFor = Exception.class)

    public String registry(String name, String password) {

        //1.开启事务
        //2.数据操作
        //3.事务提交/回滚

        //开启事务
        TransactionStatus transaction= dataSourceTransactionManager.getTransaction(definition);   //当前事务的状态
        log.info("用户注册成功");

        //用户注册
        userService.registryUser(name, password);
        //事务提交
        dataSourceTransactionManager.commit(transaction);

        return "注册成功";
    }

    @RequestMapping("/registry")
    @Transactional(isolation = Isolation.DEFAULT)   //设置事务隔离级别

    public String registry1(String name, String password) {

        //1.开启事务
        //2.数据操作
        //3.事务提交/回滚

        //开启事务
        TransactionStatus transaction= dataSourceTransactionManager.getTransaction(definition);   //当前事务的状态
        log.info("用户注册成功");

        //用户注册
        userService.registryUser(name, password);
        //事务提交
        dataSourceTransactionManager.commit(transaction);

        return "注册成功";
    }


    @RequestMapping("/registry")
    @Transactional()

    public String registry2(String name, String password) {

        //1.开启事务
        //2.数据操作
        //3.事务提交/回滚

        //开启事务
        TransactionStatus transaction= dataSourceTransactionManager.getTransaction(definition);   //当前事务的状态
        log.info("用户注册成功");

        //用户注册
        userService.registryUser(name, password);
        //事务提交
        dataSourceTransactionManager.commit(transaction);

        return "注册成功";
    }
}